import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Spin } from 'antd';
import { mainStore } from '../stores';
import { myAxios } from '../axios';
import tools from '../utils/tools';
// import './Register.css';
import './Register.less';

const Register = () => {
  const navigate = useNavigate();
  
  // 状态管理
  const [identity, setIdentity] = useState(0);
  const [form, setForm] = useState({
    name: '',
    nickName: '',
    pwd: '',
    conf_password: '',
    phone: '',
    address: '',
    isTeacher: false
  });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 表单验证配置
  const validationConfig = {
    name: {
      rule: /^[a-zA-Z0-9_]{6,20}$/,
      errorMsg: "用户名长度6-20个字符，只允许字母、数字和下划线",
    },
    nickName: {
      rule: /^.{2,20}$/,
      errorMsg: "名称长度2-20个字符",
    },
    pwd: {
      rule: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\W]{6,15}$/,
      errorMsg: "密码长度6-15个字符，必须包含字母和数字",
    },
    conf_password: {
      // 特殊处理，在验证函数中单独处理
      errorMsg: "两次输入的密码不一致",
    },
    phone: {
      rule: /^1\d{10}$/,
      errorMsg: "请输入以1开头的11位有效电话号码",
    },
    address: {
      rule: /^.{5,100}$/,
      errorMsg: "地址长度5-100个字符",
    },
  };

  // 表单输入处理
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setForm({
      ...form,
      [name]: value
    });
    
    // 实时验证
    validateField(name, value);
  };

  // 验证单个字段
  const validateField = (name, value) => {
    let error = '';
    
    if (name === 'conf_password') {
      if (value !== form.pwd) {
        error = validationConfig[name].errorMsg;
      }
    } else if (validationConfig[name]) {
      if (!validationConfig[name].rule.test(value)) {
        error = validationConfig[name].errorMsg;
      }
    }
    
    setErrors(prev => ({
      ...prev,
      [name]: error
    }));
    
    return !error;
  };

  // 验证所有字段
  const validateForm = () => {
    let isValid = true;
    const newErrors = {};
    
    // 验证每个字段
    Object.keys(form).forEach(field => {
      if (field === 'conf_password') {
        if (form[field] !== form.pwd) {
          newErrors[field] = validationConfig[field].errorMsg;
          isValid = false;
        }
      } else if (validationConfig[field]) {
        if (!validationConfig[field].rule.test(form[field])) {
          newErrors[field] = validationConfig[field].errorMsg;
          isValid = false;
        }
      }
    });
    
    setErrors(newErrors);
    return isValid;
  };

  // 页面跳转函数
  const toLogin = () => {
    navigate('/login');
  };

  // 注册函数
  const register = async () => {
    // 防止重复提交
    if (isSubmitting) {
      return;
    }

    // 表单验证
    if (!validateForm()) {
      tools.alertMsg('请检查表单填写是否正确', 'warning');
      return;
    }

    setIsSubmitting(true);
    
    try {
      // 准备请求数据
      const requestData = {
        name: form.name,
        pwd: form.pwd,
        nickName: form.nickName,
        phone: form.phone,
        address: form.address,
        // isTeacher: form.isTeacher
      };
      console.log(requestData)
      // 发送注册请求
      const response = await myAxios.post('/reg', requestData);
      console.log(response)
      // 处理响应
      if (response.data) {
        tools.alertMsg('注册成功', 'success');
        navigate('/login');
      } else {
        tools.alertMsg('注册失败，请稍后重试', 'error');
      }
    } catch (error) {
      console.error('注册请求错误:', error);
      tools.alertMsg(error.response?.data?.message || '注册失败，请稍后重试', 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="register-container">
      <div className="post"></div>
      <div className="log-shell">
        {/* 中部内容区域 */}
        <div className="middle">
          {/* 顶部导航区域 */}
          <div className="nav-tabs">
            <div className="tab" onClick={toLogin}>登录</div>
            <div className="tab active">注册</div>
          </div>
          {/* 注册表单 */}
          <div className="register-form">
            <div className="inp">
              <div className="label-error-container">
                <span className="label">用户名</span>
                {errors.name && <span className="error-msg">{errors.name}</span>}
              </div>
              
              <input 
                name="name"
                value={form.name}
                onChange={handleInputChange}
                spellCheck="false" 
                type="text" 
              />
              
            </div>
            <div className="inp">
              <div className="label-error-container">
                <span className="label">昵称</span>
                {errors.nickName && <span className="error-msg">{errors.nickName}</span>}
              </div>
              
              <input 
                name="nickName"
                value={form.nickName}
                onChange={handleInputChange}
                spellCheck="false" 
                type="text" 
              />
              
            </div>
            <div className="inp">
              {/* <span className="label">密码</span> */}
              <div className="label-error-container">
                <span className="label">密码</span>
                {errors.pwd && <span className="error-msg">{errors.pwd}</span>}
              </div>
              <input
                name="pwd"
                value={form.pwd}
                onChange={handleInputChange}
                type="password"
              />
            </div>
            <div className="inp">
              <div className="label-error-container">
                <span className="label">确认密码</span>
                {errors.conf_password && <span className="error-msg">{errors.conf_password}</span>}
              </div>
              <input
                name="conf_password"
                value={form.conf_password}
                onChange={handleInputChange}
                type="password"
              />
              
            </div>
            <div className="inp">
              <div className="label-error-container">
                <span className="label">手机号</span>
                {errors.phone && <span className="error-msg">{errors.phone}</span>}
              </div>
              
              <input 
                name="phone"
                value={form.phone}
                onChange={handleInputChange}
                spellCheck="false" 
                type="text" 
              />
              
            </div>
            <div className="inp">
              <div className="label-error-container">
                <span className="label">地址</span>
                {errors.address && <span className="error-msg">{errors.address}</span>}
              </div>
              <input 
                name="address"
                value={form.address}
                onChange={handleInputChange}
                spellCheck="false" 
                type="text" 
              />
              
            </div>
            <div className="bnt">
              <button onClick={register} disabled={isSubmitting}>
                {isSubmitting ? "注册中..." : "注册"}
              </button>
            </div>
            <div className="bottom">{identity === 0 ? '仅为家长提供注册' : '仅为教师提供注册'}</div>
          </div>
        </div>
      </div>
      {isSubmitting && <Spin tip="注册中..." fullscreen />}
    </div>
  );
};

export default Register;